package com.nsi.service.Impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.aliyun.alipay.demo.AlipayConfig;
import com.nsi.async.AsyncTask;
import com.nsi.common.Const;
import com.nsi.common.ServerResponse;
import com.nsi.service.IAliPayService;
import com.nsi.service.IOrderService;
import com.nsi.util.DateTimeUtil;
import com.nsi.util.PropertiesUtil;
import com.wechat.pay.PayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;


/**
 * @author Luo Zhen
 */
@Slf4j
@Service
public class AliPayServiceImpl implements IAliPayService {

    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private AsyncTask asyncTask;

    /**
     * 支付宝手机支付
     *
     * @param subject
     * @param body
     * @param total_fee
     * @param returnUrl
     * @return
     */
    @Override
    public void appPay(String subject, String body, String total_fee, HttpServletResponse response, String returnUrl) throws IOException {
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = PayUtil.getCurrTime() + PayUtil.getRandomString(5);
        // 超时时间
        String timeout_express = "60m";
        // 销售产品码 必填
        String product_code = "QUICK_WAP_WAY";
        // 验签
        AlipayClient client = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_fee);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步地址
        alipay_request.setReturnUrl(returnUrl);
        alipay_request.setNotifyUrl(PropertiesUtil.getProperty("alipay.callback.url"));

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * PC网页支付
     *
     * @param subject
     * @param body
     * @param total_fee
     * @param response
     * @param returnUrl
     * @throws IOException
     */
    @Override
    public void appPayHtml(String subject, String body, String total_fee, HttpServletResponse response, String returnUrl) throws IOException {
        // 商户订单统号，商户网站订单系中唯一订单号，必填
        String out_trade_no = PayUtil.getCurrTime() + PayUtil.getRandomString(5);
        // 超时时间
        String timeout_express = "60m";
        // 销售产品码(必填固定)
        String product_code = "FAST_INSTANT_TRADE_PAY";
        // 验签
        AlipayClient client = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 设置异步地址
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(PropertiesUtil.getProperty("alipay.callback.url"));
        String json = "{\"out_trade_no\":\"" + out_trade_no + "\",\"product_code\":\"" + product_code + "\",\"total_amount\":\"" + total_fee + "\",\"subject\":\"" + subject + "\",\"body\":\"" + body + "\"}";
        alipayRequest.setBizContent(json);

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();

    }

    /**
     * 支付宝回调
     *
     * @param params
     * @return
     */
    @Override
    public ServerResponse aliCallback(Map<String, String> params) {
        String totalPrice = params.get("total_amount");
        String orderNo = params.get("body");
        //如果交易成功
        if (Const.AlipayCallback.TRADE_STATUS_TRADE_SUCCESS.equalsIgnoreCase(params.get("trade_status"))) {

            log.info("************* 支付成功(支付宝异步通知) - 时间: {} *************", DateTimeUtil.dateToStr(new Date()));
            log.info("* 支付宝订单号: {}", orderNo);
            log.info("* 实际支付金额: {}", totalPrice);
            log.info("* 交易状态: {}", Const.AlipayCallback.RESPONSE_SUCCESS);
            log.info("*****************************************************************************");

            // 修改订单状态
            iOrderService.updateByOrderNo(orderNo);
            // 发送管理员邮件
            try {
                String sendMsg = "支付报回调:" + totalPrice + "元,订单号：" + orderNo + ",<支付宝支付平台>";
                asyncTask.sendAdminEmail(sendMsg);
            } catch (Exception e) {
                log.error("【支付宝回调】回调异常 msg:{}", e.getMessage());
            }
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByError();
        }
    }

    /**
     * 轮询接口
     *
     * @param orderNo
     * @return
     */
    @Override
    public ServerResponse queryOrderPayStatus(String orderNo) {
        if (StringUtils.isBlank(orderNo)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        int count = iOrderService.findOrderNoAndStatus(orderNo);
        if (count > 0) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }


}
